import 'package:sqflite/sqflite.dart';

/// 文件哈希记录模型
/// 用于存储文件路径与哈希值的映射关系
class HashFileRecord {
  int? id; // 数据库主键
  String filePath; // 文件路径
  String hash; // 文件哈希值
  int fileSize; // 文件大小（字节）
  int lastModified; // 最后修改时间戳（毫秒）
  int createdAt; // 记录创建时间戳（毫秒）
  int? uploadedAt; // 文件上传时间戳（毫秒），null表示尚未上传

  /// 文件是否已上传
  bool get isUploaded => uploadedAt != null;

  /// 构造函数
  HashFileRecord({
    this.id,
    required this.filePath,
    required this.hash,
    required this.fileSize,
    required this.lastModified,
    int? createdAt,
    this.uploadedAt,
  }) : createdAt = createdAt ?? DateTime.now().millisecondsSinceEpoch;

  /// 从Map创建哈希记录对象（用于数据库查询）
  factory HashFileRecord.fromMap(Map<String, dynamic> map) {
    return HashFileRecord(
      id: map['id'] as int,
      filePath: map['file_path'] as String,
      hash: map['hash'] as String,
      fileSize: map['file_size'] as int,
      lastModified: map['last_modified'] as int,
      createdAt: map['created_at'] as int,
      uploadedAt: map['uploaded_at'] as int?,
    );
  }

  /// 转换为Map（用于数据库插入或更新）
  Map<String, dynamic> toMap() {
    return {
      if (id != null) 'id': id,
      'file_path': filePath,
      'hash': hash,
      'file_size': fileSize,
      'last_modified': lastModified,
      'created_at': createdAt,
      'uploaded_at': uploadedAt,
    };
  }

  /// 创建数据库表
  static Future<void> createTable(Database db) async {
    await db.execute('''
      CREATE TABLE IF NOT EXISTS hash_file_records (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        file_path TEXT NOT NULL UNIQUE,
        hash TEXT NOT NULL,
        file_size INTEGER NOT NULL,
        last_modified INTEGER NOT NULL,
        created_at INTEGER NOT NULL,
        uploaded_at INTEGER
      )
    ''');

    // 创建索引以加速查询
    await db.execute(
      'CREATE INDEX IF NOT EXISTS idx_hash ON hash_file_records (hash)',
    );
    await db.execute(
      'CREATE INDEX IF NOT EXISTS idx_file_path ON hash_file_records (file_path)',
    );
    await db.execute(
      'CREATE INDEX IF NOT EXISTS idx_uploaded ON hash_file_records (uploaded_at)',
    );
  }

  /// 标记文件为已上传
  void markAsUploaded() {
    uploadedAt = DateTime.now().millisecondsSinceEpoch;
  }

  @override
  String toString() {
    return 'HashFileRecord{id: $id, filePath: $filePath, hash: $hash, fileSize: $fileSize, lastModified: $lastModified, uploaded: $isUploaded}';
  }
}
